import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:largefriends/res/lf_color.dart';
import 'package:largefriends/widgets/lf_image_picker/lf_asset_picker_delegate.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

class LfImagePicker {
  static ThemeData themeDatePicker = ThemeData.dark();

  static pickerImage(
    void Function(List<AssetEntity>) handler, {
    bool onlyCamera = false,
    List<AssetEntity>? selected,
    int maxCount = 1,
  }) async {
    if (onlyCamera) {
      var result = await CameraPicker.pickFromCamera(
        Get.context!,
        pickerConfig: const CameraPickerConfig(enableRecording: true),
      );
      if (result != null) {
        handler.call([result]);
      } else {
        handler.call([]);
      }
      return;
    }
    LfAssetPickerDelegate delegate = LfAssetPickerDelegate();
    var result = await delegate.pickAssets(
      Get.context!,
      pickerConfig: AssetPickerConfig(
          maxAssets: maxCount,
          selectedAssets: selected,
          pickerTheme: themeDatePicker,
          requestType: RequestType.image,
          specialItemPosition: SpecialItemPosition.prepend,
          specialItemBuilder: (
            BuildContext context,
            AssetPathEntity? path,
            int length,
          ) {
            if (path?.isAll != true) {
              return null;
            }
            final AssetPicker<AssetEntity, AssetPathEntity> picker =
                context.findAncestorWidgetOfExactType()!;
            final DefaultAssetPickerBuilderDelegate builder =
                picker.builder as DefaultAssetPickerBuilderDelegate;

            return Semantics(
              button: true,
              child: InkWell(
                onTap: () async {
                  final AssetEntity? result = await _pickFromCamera(context);
                  if (result == null) {
                    return;
                  }
                  final DefaultAssetPickerProvider p = builder.provider;
                  await p.switchPath(
                    PathWrapper<AssetPathEntity>(
                      path: await p.currentPath!.path.obtainForNewProperties(),
                    ),
                  );
                  p.selectAsset(result);
                },
                child: Center(
                  child: Icon(
                    Icons.camera_enhance,
                    size: 42.0,
                    color: color210215,
                  ),
                ),
              ),
            );
          }),
    );
    handler.call(result ?? []);
  }

  static Future<AssetEntity?> _pickFromCamera(BuildContext c) {
    return CameraPicker.pickFromCamera(
      c,
      pickerConfig: const CameraPickerConfig(
        enableRecording: false,
        preferredLensDirection: CameraLensDirection.front,
      ),
    );
  }
}
